package com.chen.hotel.Service.impl;

import com.chen.hotel.Service.OrderService;
import com.chen.hotel.Service.RoomService;
import com.chen.hotel.dao.OrderDao;
import com.chen.hotel.domain.Order;
import com.chen.hotel.domain.Room;
import com.chen.hotel.enums.OrderStatusEnum;
import com.chen.hotel.enums.RoomStatusEnum;
import com.chen.hotel.exception.HotelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao dao;

    @Autowired
    private RoomService roomService;

    @Override
    @Transactional
    public Order create(Order order) {
        Room room = this.roomService.getRoomById(order.getRoomId());
        if(room.getStatus() == RoomStatusEnum.HASBEENIN.getCode()) {
            throw new HotelException(401, "房间已入住了用户");
        }
        room.setStatus(RoomStatusEnum.HASBEENIN.getCode());
        this.roomService.update(room);
        return this.dao.save(order);
    }

    @Override
    public void cancel(Integer id, String cardId) {
        Order order = this.findById(id);
        if(!order.getCardId().equals(cardId)){
            throw new HotelException(403, "你没有权限操作这个订单");
        }
        order.setStatus(OrderStatusEnum.CANCEL.getCode());
        this.dao.save(order);
    }

    @Override
    public Order findById(Integer id) {
        return this.dao.findById(id).get();
    }

    @Override
    public Page<Order> findAll(Pageable request) {
        return this.dao.findAll(request);
    }

    @Override
    @Transactional
    public Order updateStatus(Integer status, Integer id) {
        Order order = this.findById(id);
        order.setStatus(status);
        Room room = this.roomService.getRoomById(order.getRoomId());
        if(status == OrderStatusEnum.CANCEL.getCode()){
            // 更新房间状态
            room.setStatus(RoomStatusEnum.SPARE.getCode());
        }else if(status == OrderStatusEnum.FINISH.getCode()){
            room.setStatus(RoomStatusEnum.CLEAN.getCode());
        }
        this.roomService.update(room);
        return this.dao.save(order);
    }

    @Override
    public Page<Order> findByStatus(Integer status, Pageable request) {
        return this.dao.findByStatus(status, request);
    }
}
